package com.goldcn.classify.service;

import com.goldcn.classify.dao.ClassifyToAttrDefMapper;
import com.goldcn.classify.dto.ObjAndAttrDef;
import com.goldcn.classify.model.ClassifyToAttrDef;
import com.goldcn.common.consts.RestConst;
import com.goldcn.common.exception.ServiceException;
import com.goldcn.common.util.UuidUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2016/5/25.
 */
@Service("classifyToAttrDefService")
@Transactional
public class ClassifyToAttrDefService {
    @Autowired
    private ClassifyToAttrDefMapper classifyToAttrDefMapper;

    public int deleteByPrimaryKey(String ctaID){
        return classifyToAttrDefMapper.deleteByPrimaryKey(ctaID);
    }

    public int insertSelective(ClassifyToAttrDef record){
        return classifyToAttrDefMapper.insertSelective(record);
    }

    public ClassifyToAttrDef selectByPrimaryKey(String ctaID){
        return classifyToAttrDefMapper.selectByPrimaryKey(ctaID);
    }

    public int updateByPrimaryKeySelective(ClassifyToAttrDef record){
        return classifyToAttrDefMapper.updateByPrimaryKeySelective(record);
    }

    @Transactional
    public boolean addByClazzAndAttr(ObjAndAttrDef list){
        //添加
        for(ClassifyToAttrDef classifyToAttrDef:list.getClassifyToAttrDefs()){
            //判断是否已经关联
            Map<String,String> parm=new HashMap<String,String>();
            parm.put("clazzObjID",classifyToAttrDef.getClazzObjID());
            parm.put("cfadID",classifyToAttrDef.getCfadID());
            if(classifyToAttrDefMapper.selectByClazzAndAttr(parm).isEmpty()){
                classifyToAttrDef.setCtaID(UuidUtils.uuid());
                classifyToAttrDefMapper.insertSelective(classifyToAttrDef);
            }else{
                throw new ServiceException("品类:"+classifyToAttrDef.getClazzObjID()+" 属性:"+
                        classifyToAttrDef.getCfadID()+"已经关联", RestConst.ErrorCode.DATABASE_ERROR);
            }
        }
        return true;
    }

    public List<ClassifyToAttrDef> selectByClazzAndAttr(Map<String,String> parm){
        return classifyToAttrDefMapper.selectByClazzAndAttr(parm);
    }

}
